/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[TokenGenerator.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package session;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Token生成器[Struts1的源码]
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TokenGenerator {

	private static final String TOKEN_IN_HIDDEN = "TOKEN_IN_HIDDEN";
	private static final String TOKEN_IN_SESSION = "TOKEN_IN_SESSION";

	private static TokenGenerator instance = new TokenGenerator();

	// 前一个Token值
	private long previousTokenValue;

	protected TokenGenerator() {
		super();
	}

	public static TokenGenerator getInstance() {
		return instance;
	}

	/**
	 * 验证Token是否有效
	 * 
	 * @param request
	 * @return
	 */
	public synchronized boolean isTokenValid(HttpServletRequest request) {
		return this.isTokenValid(request, false);
	}

	/**
	 * 验证Token是否有效
	 * 
	 * @param request
	 * @param reset
	 * @return
	 */
	public synchronized boolean isTokenValid(HttpServletRequest request, boolean reset) {
		HttpSession session = request.getSession();

		if (session == null) {
			return false;
		}

		String tokenInSession = (String) session.getAttribute(TOKEN_IN_SESSION);

		if (tokenInSession == null) {
			return false;
		}

		if (reset) {
			this.clearToken(request);
		}

		String tokenInHidden = request.getParameter(TOKEN_IN_HIDDEN);
		if (tokenInHidden == null) {
			return false;
		}

		return tokenInHidden.equals(tokenInHidden);
	}

	/**
	 * 清除Session中的Token
	 * 
	 * @param request
	 */
	public synchronized void clearToken(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return;
		}

		session.removeAttribute(TOKEN_IN_SESSION);
	}

	/**
	 * 将Token保存到Session中
	 * 
	 * @param request
	 * @return
	 */
	public synchronized String saveTokenInSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String token = this.generateToken(request);
		if (token != null) {
			session.setAttribute(TOKEN_IN_SESSION, token);
		}
		return token;
	}

	/**
	 * 根据SessionID生成Token
	 * 
	 * @param request
	 * @return
	 */
	public synchronized String generateToken(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return generateToken(session.getId());
	}

	public synchronized String generateToken(String id) {
		try {
			long currentTokenValue = System.currentTimeMillis();
			if (currentTokenValue == previousTokenValue) {
				currentTokenValue++;
			}

			previousTokenValue = currentTokenValue;

			byte[] now = new Long(currentTokenValue).toString().getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(id.getBytes());
			md.update(now);

			return toHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	private String toHex(byte[] buffer) {
		StringBuffer stringBuffer = new StringBuffer(buffer.length * 2);

		for (int i = 0; i < buffer.length; i++) {
			stringBuffer.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
			stringBuffer.append(Character.forDigit(buffer[i] & 0x0f, 16));
		}

		return stringBuffer.toString();
	}
}
